<template>
  <div class="list-table" style="height: 100%; overflow: auto">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['fund:expenseFeeDetail:view']"
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="exportHandle"
        >{{ $t("导出") }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['fund:expenseFeeDetail:edit']"
          type="warning"
          icon="el-icon-edit"
          size="mini"
          @click="batchEditHandle"
        >{{ $t("批量编辑") }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-if="batchEdit"
          v-hasPermi="['fund:expenseFeeDetail:edit']"
          type="success"
          icon="el-icon-refresh-right"
          size="mini"
          @click="calculateExpenseAmount"
        >{{ $t("计算") }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-if="batchEdit"
          size="mini"
          @click="cancel"
        >{{ $t("取消") }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-if="batchEdit"
          v-hasPermi="['fund:expenseFeeDetail:edit']"
          type="primary"
          size="mini"
          @click="checkBatchSaveHandle"
        >{{ $t("保存") }}</el-button>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="fundExpenseFeeDetailList" border row-key="id" :show-summary="true" :summary-method="getSummaries" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="40" align="center" />
      <el-table-column :label="$t('序号')" type="index" align="center" show-overflow-tooltip width="50">
        <template slot-scope="scope">
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('出资人名称')" align="center" prop="userName" min-width="180" show-overflow-tooltip />
      <!--      <el-table-column :label="$t('出资人类型')" align="center" prop="investorsType" :formatter="investorsTypeOptionsFormat" min-width="140" show-overflow-tooltip />-->
      <el-table-column :label="$t('合伙人类型')" align="center" prop="partnerType" :formatter="partnerTypeOptionsFormat" min-width="140" show-overflow-tooltip />
      <el-table-column :label="$t('费用分摊规则')" align="center" prop="feeRule" :formatter="feeRuleOptionsFormat" min-width="180" show-overflow-tooltip />
      <el-table-column :label="$t('计算基数') + $t('(元)')" align="center" prop="calculationBase" min-width="180">
        <template slot-scope="scope">
          <span class="money-text">{{ moneyFormat(scope.row.calculationBase, 'rate') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('费用金额') + $t('(元)')" align="center" prop="amountMoney" min-width="180">
        <template slot-scope="scope">
          <span v-if="!batchEdit" class="money-text">{{ moneyFormat(scope.row.amountMoney) }}</span>
          <Money v-else v-model="scope.row.amountMoney" :placeholder="$t('费用金额')" @change="calculateListSum" />
        </template>
      </el-table-column>
      <el-table-column :label="$t('操作')" fixed="right" align="center" class-name="small-padding fixed-width" width="220">
        <template slot-scope="scope">
          <!--          <el-button-->
          <!--            v-hasPermi="['fund:expenseFeeDetail:edit']"-->
          <!--            size="small"-->
          <!--            type="text"-->
          <!--            icon="el-icon-edit"-->
          <!--            @click="updateHandle(scope.row)"-->
          <!--          >{{ $t('修改') }}</el-button>-->
          <el-button
            v-hasPermi="['fund:expenseFeeDetail:remove']"
            size="small"
            type="text"
            icon="el-icon-delete"
            @click="deleteHandle(scope.row)"
          >{{ $t('删除') }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改基金费用明细对话框 -->
    <el-dialog :title="title" :visible.sync="formOpen" :close-on-click-modal="false" :lock-scroll="false" append-to-body>
      <fundExpenseFeeDetailForm ref="fundExpenseFeeDetailForm" />
    </el-dialog>
  </div>
</template>

<script>
import {
  batchSaveFundExpenseFeeDetail,
  calculateExpenseAmount,
  delFundExpenseFeeDetail,
  getFundExpenseFeeDetailSum,
  listFundExpenseFeeDetail
} from '@/api/fund/expenseFeeDetail/fundExpenseFeeDetail'
import fundExpenseFeeDetailForm from './fundExpenseFeeDetailForm'
export default {
  components: {
    fundExpenseFeeDetailForm
  },
  data() {
      return {
          // 遮罩层
          loading: true,
          // 总条数
          total: 0,
          // 基金费用明细表格数据
          fundExpenseFeeDetailList: [],
          fundExpenseFeeDetailSum: {},
          // 弹出层标题
          title: '基金费用明细',
          // 是否显示弹出层
          formOpen: false,
          investorsTypeOptions: [],
          partnerTypeOptions: [],
          feeRuleOptions: [],
          // 查询参数
          queryParams: {
              expenseId: undefined,
              pageNum: 1,
              pageSize: 10
          },
          // 表单参数
          form: {},
          // 表单校验
          rules: {},
          ids: [],
          changeBtn: false,
          amountMoney: undefined,
          batchEdit: false
      }
  },
  created() {
    // 出资人类型
    this.getDicts('fund_investor_type').then(response => {
      this.investorsTypeOptions = response.data
    })
    // 合伙人类型
    this.getDicts('partner_type').then(response => {
      this.partnerTypeOptions = response.data
    })
    this.getDicts('fund_share_way').then(response => {
      this.feeRuleOptions = response.data
    })
  },
  methods: {
    /** 查询基金费用明细列表 */
    getList() {
      this.loading = true
      listFundExpenseFeeDetail(this.queryParams).then(response => {
        getFundExpenseFeeDetailSum(this.queryParams).then(res => {
          this.fundExpenseFeeDetailSum = res.data
        })
        this.fundExpenseFeeDetailList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    getFundExpenseFeeDetail(row) {
      this.loading = true
      this.batchEdit = false
      this.queryParams.expenseId = row.id
      this.amountMoney = row.amountMoney
      this.getList()
    },
    // 出资人类型
    investorsTypeOptionsFormat(row) {
      return this.selectDictLabel(this.investorsTypeOptions, row.investorsType)
    },
    // 合伙人类型
    partnerTypeOptionsFormat(row) {
      return this.selectDictLabel(this.partnerTypeOptions, row.partnerType)
    },
    // 费用分摊规则
    feeRuleOptionsFormat(row) {
      return this.selectDictLabel(this.feeRuleOptions, row.feeRule)
    },
    // 表单重置
    reset() {
        this.form = {
            id: undefined,
            expenseId: undefined,
            fundId: undefined,
            userName: undefined,
            investorsType: undefined,
            investorId: undefined,
            calculationBase: undefined,
            amountMoney: undefined,
            feeRule: undefined,
            remark: undefined,
            createBy: undefined,
            createTime: undefined,
            updateBy: undefined,
            updateTime: undefined
        }
        this.resetForm('form')
    },
    /** 修改按钮操作 */
    updateHandle(row) {
      this.formOpen = true
      this.title = this.$t('修改管理费明细')
      this.$nextTick(() => {
        // 调用form页面的 init 方法初始化数据
        this.$refs.fundExpenseFeeDetailForm.init(row)
      })
    },
    /** 删除按钮操作 */
    deleteHandle(row) {
      this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(function() {
        return delFundExpenseFeeDetail(row.id)
      }).then(() => {
        this.getList()
        this.msgSuccess(this.$t('删除成功'))
      }).catch(function() {
      })
    },
    // 批量编辑
    batchEditHandle() {
      if (this.fundExpenseFeeDetailList.length === 0) {
        return this.msgError(this.$t('基金费用明细为空'))
      }
      if (this.queryParams.pageSize !== 200) {
        this.queryParams.pageSize = 200
        this.getList()
      }
      this.batchEdit = true
    },
    // 取消
    cancel() {
      this.loading = true
      this.getList()
      this.batchEdit = false
      this.loading = false
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
    },
    calculateExpenseAmount() {
      if (this.fundExpenseFeeDetailList.length === 0) {
        return this.msgError(this.$t('基金费用明细为空，不可计算！'))
      }
      let dataList = []
      if (this.ids && this.ids.length > 0) {
        this.fundExpenseFeeDetailList.forEach((detail) => {
          if (this.ids.includes(detail.id)) {
            dataList.push(detail)
          }
        })
      } else {
        dataList = this.fundExpenseFeeDetailList
      }
      calculateExpenseAmount(this.queryParams.expenseId, dataList).then(response => {
        if (response.data) {
          let amountMoneySum = 0
          this.fundExpenseFeeDetailList.forEach(detail => {
            const mapItem = response.data.find(mapItem => mapItem.id === detail.id)
            if (mapItem) {
              detail.amountMoney = mapItem.amountMoney
            } else {
              detail.amountMoney = 0
            }
            amountMoneySum += detail.amountMoney
          })
          this.fundExpenseFeeDetailSum.amountMoney = amountMoneySum
        }
        this.msgSuccess(this.$t('计算完成'))
      })
    },
    calculateListSum() {
      let amountMoneySum = 0
      this.fundExpenseFeeDetailList.forEach((detail) => {
        if (detail.amountMoney) {
          amountMoneySum += detail.amountMoney
        }
      })
      this.fundExpenseFeeDetailSum.amountMoney = amountMoneySum
    },
    checkBatchSaveHandle() {
      if (this.fundExpenseFeeDetailList.length === 0) {
        return this.msgError(this.$t('基金费用明细为空，不可保存！'))
      }
      if (this.fundExpenseFeeDetailSum.amountMoney !== this.amountMoney) {
        this.$confirm(this.$t('修改后的明细金额合计与基金费用金额不一致，保存后将同步修改费用金额，是否确认?'), this.$t('警告'), {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: 'warning'
        }).then(() => {
          this.batchSaveHandle()
          this.amountMoney = this.fundExpenseFeeDetailSum.amountMoney
        }).catch(function() {
        })
      } else {
        this.batchSaveHandle()
      }
    },
    batchSaveHandle() {
      this.loading = true
      batchSaveFundExpenseFeeDetail(this.fundExpenseFeeDetailList, this.queryParams.expenseId).then(response => {
        if (response.code === 200) {
          this.msgSuccess(this.$t('保存成功'))
        } else {
          this.msgError(response.msg)
        }
        this.batchEdit = false
        this.getList()
        if (this.$parent.$parent.getList !== undefined) {
          this.$parent.$parent.getList()
          this.$parent.$parent.$parent.$parent.getList()
        }
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 合计
    getSummaries(param) {
      const { columns } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 1) {
          sums[index] = '合计'
        } else if (index === 5) {
          sums[index] = this.moneyFormat(this.fundExpenseFeeDetailSum.calculationBase, 'rate')
        } else if (index === 6) {
          sums[index] = this.moneyFormat(this.fundExpenseFeeDetailSum.amountMoney)
        } else {
          sums[index] = ''
        }
      })
      return sums
    },
    exportHandle() {
      this.downLoadExcel('/expenseFeeDetail/fundExpenseFeeDetail/export', this.queryParams)
    }
  }
}
</script>
